<template>
  <div class="home">
    <van-nav-bar
      title="房贷计算器"
      left-arrow
      @click-left="onClickLeft"
    />
    
    <div class="content">
      <!-- 城市选择 -->
      <van-cell-group inset>
        <van-field
          v-model="cityName"
          label="城市"
          placeholder="请选择城市"
          readonly
          @click="showCityPicker = true"
        />
      </van-cell-group>

      <!-- 贷款类型选择 -->
      <van-cell-group inset title="贷款信息" class="mt-3">
        <van-field
          v-model="loanType"
          label="贷款类型"
          placeholder="请选择贷款类型"
          readonly
          @click="showLoanTypePicker = true"
        />
        <van-popup v-model:show="showLoanTypePicker" position="bottom">
          <van-picker
            :columns="loanTypeOptions"
            title="选择贷款类型"
            @confirm="onLoanTypeConfirm"
            @cancel="showLoanTypePicker = false"
          />
        </van-popup>

        <!-- 贷款金额 -->
        <van-field
          v-model="amount"
          type="number"
          label="贷款金额"
          placeholder="请输入贷款金额"
          right-icon="after-sale"
        >
          <template #right-icon>万元</template>
        </van-field>

        <!-- 贷款年限 -->
        <van-field
          v-model="years"
          type="number"
          label="贷款年限"
          placeholder="请选择贷款年限"
          readonly
          @click="showYearsPicker = true"
        />
        <van-popup v-model:show="showYearsPicker" position="bottom">
          <van-picker
            :columns="yearsOptions"
            title="选择贷款年限"
            @confirm="onYearsConfirm"
            @cancel="showYearsPicker = false"
          />
        </van-popup>

        <!-- 贷款利率 -->
        <van-field
          v-if="loanType !== 'combination'"
          :value="currentRate + '%'"
          label="贷款利率"
          readonly
        />
      </van-cell-group>

      <!-- 计算按钮 -->
      <div class="button-group">
        <van-button type="primary" block @click="calculate">开始计算</van-button>
      </div>
    </div>

    <!-- 城市选择弹窗 -->
    <van-popup v-model:show="showCityPicker" position="bottom">
      <van-picker
        :columns="cityColumns"
        title="选择城市"
        @confirm="onCityConfirm"
        @cancel="showCityPicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useLoanStore } from '@/stores/loan'
import { getCityList } from '@/api/loan'
import type { CityInfo } from '@/types/api'

const router = useRouter()
const loanStore = useLoanStore()

// 城市选择相关
const showCityPicker = ref(false)
const cityName = ref(loanStore.cityName)
const cityList = ref<CityInfo[]>([])
const cityColumns = computed(() => {
  return cityList.value.map(city => ({
    text: city.name,
    value: city.code
  }))
})

// 当前利率
const currentRate = computed(() => {
  return loanStore.loanType === 'commercial' ? 
    loanStore.commercialRate : loanStore.fundRate
})

// 获取城市列表
const fetchCityList = async () => {
  try {
    cityList.value = await getCityList()
  } catch (error) {
    console.error('获取城市列表失败:', error)
  }
}

// 城市选择确认
const onCityConfirm = async (value: { text: string, value: string }) => {
  showCityPicker.value = false
  cityName.value = value.text
  await loanStore.updateCityInfo(value.value, value.text)
}

onMounted(() => {
  fetchCityList()
})

// 贷款类型相关
const showLoanTypePicker = ref(false)
const loanType = ref('商业贷款')
const loanTypeOptions = [
  { text: '商业贷款', value: 'commercial' },
  { text: '公积金贷款', value: 'fund' },
  { text: '组合贷款', value: 'combination' }
]

// 贷款金额
const amount = ref('')

// 贷款年限相关
const showYearsPicker = ref(false)
const years = ref('30年')
const yearsOptions = Array.from({length: 30}, (_, i) => ({
  text: `${i + 1}年`,
  value: i + 1
}))

// 事件处理
const onClickLeft = () => {
  router.back()
}

const onLoanTypeConfirm = (value: { text: string, value: string }) => {
  loanType.value = value.text
  showLoanTypePicker.value = false
}

const onYearsConfirm = (value: { text: string, value: number }) => {
  years.value = value.text
  showYearsPicker.value = false
}

const calculate = () => {
  // 保存数据到 store
  loanStore.updateLoanInfo({
    loanType: loanTypeOptions.find(option => option.text === loanType.value)?.value || 'commercial',
    amount: Number(amount.value),
    years: yearsOptions.find(option => option.text === years.value)?.value || 30,
  })
  // 跳转到结果页
  router.push('/payment-plan')
}
</script>

<style lang="scss" scoped>
@use '@/assets/styles/variables' as v;

.home {
  height: 100%;
  background-color: v.$background-color;

  .content {
    padding: 16px;
  }

  .button-group {
    margin-top: 24px;
    padding: 0 16px;
  }

  .mt-3 {
    margin-top: 12px;
  }
}
</style> 